<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <link th:replace="head::headerFragment('IQL查询')">
    <meta charset="UTF-8"/>
    <title>IQL</title>
    <style type="text/css">
    </style>
</head>
<body>

<div id="body_1">
    <div id="body_left">
        <div class="body_lr_top">
            <div class="ibox-content left_tab_box">
                <div class="tabs-container" style="margin-top: 20px">
                    <ul class="nav nav-tabs" style="margin-left: 20px">
                        <li class="active"><a data-toggle="tab" href="#tab-4" aria-expanded="true">JobScript</a></li>
                        <li class=""><a data-toggle="tab" href="#tab-5" aria-expanded="false">DataBase</a></li>
                        <li class="tab_stream_job"><a data-toggle="tab" href="#tab-6" aria-expanded="false">StreamJob</a></li>
                    </ul>
                    <div class="tab-content" style="margin-left: 20px">
                        <div id="tab-4" class="tab-pane active">
                            <div class="left_tab">
                                <ul id="treeJobScript" class="ztree"></ul>
                            </div>
                        </div>
                        <div id="tab-5" class="tab-pane">
                            <div class="left_tab">
                                <ul id="treeHiveDB" class="ztree"></ul>
                            </div>
                        </div>
                        <div id="tab-6" class="tab-pane">
                            <div class="left_tab">
                                <table id="active-streamjob-table"
                                       data-classes="table table-hover table-condensed  table-no-head"
                                       data-mobile-responsive="true">
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    <div class="snippet-code-resizer-X ui-draggable-x" data-bind="aceResizer : { ace: ace, target: '.ace-container-resizable', onStart: hideFixedHeaders, onStop: redrawFixedHeaders }">
    </div>
    <div id="body_right">

        <div id="body_lr_bot">
            <div style="height: 60px;width: 100%;background-color: #f0f0f0;position: relative">
                <form role="form" class="form-inline" id="execForm" style="position: absolute;left: 30px; bottom: 10px;right: 0;">
                    <div class="form-group" style="margin-right: 15px;">
                        <a class="btn" onclick="execIQL()" title="execute"><i class="fa fa-play"></i></a>
                    </div>
                    <div class="form-group" style="margin-right: 15px;">
                        <a class="btn" onclick="saveScript()" title="save query as..."><i class="fa fa-save"></i></a>
                    </div>
                    <div class="form-group">
                        <a class="btn" onclick="formatIQL()" title="format the current iql query"><i
                                class="fa fa-indent"></i></a>
                    </div>

                    <div class="form-group" style="float: right;margin-right: 10px">
                        <div class="btn-group" data-toggle="buttons">
                            <label class="btn btn-primary btn-outline active">
                                <input name="findType" type="radio" value="iql">SQL
                            </label>
                            <label class="btn btn-primary btn-outline">
                                <input name="findType" type="radio" value="code">Code
                            </label>
                        </div>
                    </div>
                </form>
                <div class="loading" style="display: none;position: absolute;left: 40px; bottom: 2px;right: 0;">
                    <div class="form-group">
                        <a class="btn" onclick="stopQuery()" title="stop query ..." style="color: red;padding: 0px 0px;"><i
                                class="fa fa-stop"></i></a>
                        <input id="iqlId" type="hidden" name="field＿name" value=""/>
                    </div>
                </div>
            </div>

            <div id="iql_input">
                <textarea id="iql" rows="15" placeholder="Example: SELECT * FROM tablename, or press CTRL + space"
                          style="width: 100%"></textarea>
            </div>
            <div id="variable" style="display: none">
                <ul data-bind="foreach: variables" style="list-style:none">
                    <li>
                        <div class="input-prepend">
                            <span class="muted" data-bind="text:name"></span>
                            <input class="input-medium" type="text" data-bind="value:value"
                                   placeholder="Variable value"/>
                        </div>
                    </li>
                </ul>
            </div>
            <div id="errorMessage"
                 style="min-height:10px; max-height:350px;width: 100%;background-color: #f7f7f7;padding-bottom: 20px;padding-left: 30px;padding-right: 30px;overflow:scroll;display: none">
                <pre style="color:red;"></pre>
            </div>
            <div class="loading" style="background-color: #f0f0f0; display: none; ">
                <div class="sk-spinner sk-spinner-wave" style="width: 100px;">
                    <div class="sk-rect1"></div>
                    <div class="sk-rect2"></div>
                    <div class="sk-rect3"></div>
                    <div class="sk-rect4"></div>
                    <div class="sk-rect5"></div>
                </div>
            </div>
            <div class="ibox-content">
                <div class="snippet-code-resizer ui-draggable" data-bind="aceResizer : { ace: ace, target: '.ace-container-resizable', onStart: hideFixedHeaders, onStop: redrawFixedHeaders }">
                    <i class="fa fa-ellipsis-h"></i>
                </div>
                <div class="tabs-container" style="margin-top: 20px">
                    <ul class="nav nav-tabs" style="margin-left: 20px">
                        <li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true">Query History</a>
                        </li>
                        <li class=""><a id="results-tab" data-toggle="tab" href="#tab-2"
                                        aria-expanded="false">Result</a>
                        </li>
                    </ul>
                    <div class="tab-content" style="margin-left: 20px">
                        <div id="tab-1" class="tab-pane active">
                            <div class="panel-body">
                                <table id="history-list-table"
                                       data-classes="table table-hover table-condensed"
                                       data-mobile-responsive="true">
                                </table>
                            </div>
                        </div>
                        <div id="tab-2" class="tab-pane">
                            <div class="panel-body">
                                <form role="form" class="form-inline" id="downloadForm" style="display: none;">
                                    <div class="form-group">
                                        <div class="dropdown">
                                            <button class="btn dropdown-toggle" data-toggle="dropdown"
                                                    id="rankType-dropdown" aria-expanded="false">
                                                <i class="fa fa-download"></i>
                                                <span class="caret"></span>
                                            </button>
                                            <ul class="dropdown-menu" role="menu" aria-labelledby="rankType-dropdown">
                                                <li><a onclick="downloadFile('json')">json</a></li>
                                                <li><a onclick="downloadFile('csv')">csv</a></li>
                                                <li><a onclick="downloadFile('excel')">excel</a></li>
                                            </ul>
                                        </div>
                                    </div>
                                </form>
                                <table id="results-list-table" data-classes="table table-hover table-condensed"
                                       data-mobile-responsive="true">
                                    <div id="result-content"
                                         style="width: 100%;background-color: #f7f7f7;display: none">
                                        <pre></pre>
                                    </div>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="rMenu" style="display: none">
    <ul>
        <li id="m_add" onclick="addTreeNodeDir();">新建节点</li>
        <li id="m_rename" onclick="renameTreeNode();">重命名</li>
        <li id="m_del" onclick="removeTreeNode();">删除</li>
    </ul>
</div>

<div id="modal-share" class="modal fade" aria-hidden="true" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <div class="row">
                    <div class="col-sm-10 b-r">
                        <form role="form">
                            <div class="form-group">
                                <label class="control-label">请保管好连接，勿将连接分享其他无关人员！</label>
                                <input type="text" readonly="readonly" class="form-control" id="urlSign" name="urlSign">
                                <span id="icon-error" class="help-block m-b-none"></span>
                            </div>
                            <div class="pull-right m-t-n-xs">
                                <button class="btn btn-sm btn-default" data-dismiss="modal" id="close"><strong>关闭</strong>
                                </button>
                                <button class="btn btn-sm btn-default" data-dismiss="modal" onclick="copyUrl()">点击复制链接</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<SCRIPT LANGUAGE="JavaScript">
    var js_setting = {
        view: {
            selectedMulti: false
        },
        data: {
            simpleData: {
                enable: true,
                pIdKey: "pid",
                rootPId: 0
            }
        },
        check: {
            enable: false
        },
        edit: {
            enable: true,
            showRemoveBtn: false,
            showRenameBtn: false
        },
        callback: {
            onRightClick: OnRightClick,
            beforeRemove: zTreeBeforeRemove,
            beforeDrop: zTreeBeforeDrop,
            beforeAsync: zTreeBeforeAsync,
            beforeRename: zTreeBeforeRename,
            onExpand: zTreeOnExpand,
            onClick: zTreeOnClickScript,
            onAsyncSuccess: zTreeOnAsyncSuccess
        },
        async: {
            enable: true,
            autoParam: ['id'],
            url: '/jobScript/tree',
            type: 'get'
        }
    };

    // 默认展开目录树
    var curStatus = "init", curAsyncCount = 0, asyncForAll = false,treeId="treeJobScript";
    var goAsync = false;
    function expandAll() {
        if (!check()) {
            return;
        }
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        if (asyncForAll) {
            zTree.expandAll(true);
        } else {
            expandNodes(zTree.getNodes());
            if (!goAsync) {
                curStatus = "";
            }
        }
    }
    function expandNodes(nodes) {
        if (!nodes) return;
        curStatus = "expand";
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        for (var i=0, l=nodes.length; i<l; i++) {
            zTree.expandNode(nodes[i], true, false, false);
            if (nodes[i].isParent && nodes[i].zAsync) {
                expandNodes(nodes[i].children);
            } else {
                goAsync = true;
            }
        }
    }

    function check() {
        if (curAsyncCount > 0) {
            return false;
        }
        return true;
    }

    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
        // $.fn.zTree.getZTreeObj(treeId).expandAll(true);
        expandAll()
    }

    function zTreeOnClickScript(event, treeId, treeNode) {
        if (treeNode.isParent == 0) {
            var data = {
                id: treeNode.id
            };
            $.ajax({
                type: 'GET',
                url: '/jobScript/getScript',
                data: data,
                dataType: 'json',
                success: function (data) {
                    if (data.script != null) {
                        window.editor.setValue(data.script);
                    } else {
                        window.editor.setValue("");
                    }
                },
                error: function (err) {
                }
            })
        }else{
            var zTree = $.fn.zTree.getZTreeObj(treeId);
            zTree.expandNode(treeNode, null, null, null);
        }
    }

    function zTreeBeforeAsync(treeId, treeNode) {
        return true;
    }

    function OnRightClick(event, treeId, treeNode) {
        if (treeNode.name == "mc") {
            zTree.cancelSelectedNode();
            showRMenu("root", event.clientX, event.clientY);
        } else if (treeNode && !treeNode.noR) {
            zTree.selectNode(treeNode);
            showRMenu("node", event.clientX, event.clientY);
        }
    }

    function showRMenu(type, x, y) {
        $("#rMenu").show();
        $("#rMenu ul").show();
        if (type == "root") {
            $("#m_del").hide();
        } else {
            $("#m_add").show();
            $("#m_rename").show();
            $("#m_del").show();
        }
        rMenu.css({"top": y + "px", "left": x + "px", "visibility": "visible"});

        $("body").bind("mousedown", onBodyMouseDown);
    }

    function hideRMenu() {
        if (rMenu) rMenu.css({"visibility": "hidden"});
        $("body").unbind("mousedown", onBodyMouseDown);
    }

    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            rMenu.css({"visibility": "hidden"});
        }
    }

    var addCount = 1;

    function addTreeNodeDir() {
        hideRMenu();
        var newNode = {name: "增加" + (addCount++)};
        var newNode_;
        if (zTree.getSelectedNodes()[0]) {
            newNode_ = zTree.addNodes(zTree.getSelectedNodes()[0], newNode);
        } else {
            newNode_ = zTree.addNodes(zTree.getNodesByParam("name", "mc", null)[0], newNode);
        }
        zTree.editName(newNode_[0]);
    }

    //使节点处于编辑状态
    function renameTreeNode() {
        hideRMenu();
        zTree.editName(zTree.getSelectedNodes()[0]);
    }

    //删除节点
    function removeTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        if (nodes && nodes.length > 0) {
            if (nodes[0].children && nodes[0].children.length > 0) {
                var msg = "要删除的节点是父节点，如果删除将连同子节点一起删掉。\n\n请确认！";
                if (confirm(msg) == true) {
                    zTreeBeforeRemove(nodes[0].id, nodes[0]);
                    zTree.removeNode(nodes[0]);
                }
            } else {
                zTreeBeforeRemove(nodes[0].id, nodes[0]);
                zTree.removeNode(nodes[0]);
            }
        }
    }

    //删除节点（与后端交互）
    function zTreeBeforeRemove(treeId, treeNode) {
        // if(treeNode.children&&treeNode.children.length) return false;
        var isParent = 1;
        if (!treeNode.getNextNode() && !treeNode.getPreNode()) {
            isParent = 0
        }
        var data = {
            id: treeNode.id,
            pid: treeNode.pid,
            isParent: isParent
        };
        $.ajax({
            type: 'POST',
            url: '/jobScript/remove',
            data: data,
            success: function (data) {
                // var zTree = $.fn.zTree.getZTreeObj(treeId);
                // zTree.removeNode(treeNode);
                toastr.success('Modify successfully!', 'Success')
            },
            error: function (err) {
                toastr.error('An error has occurred.', 'Error!')
            }
        });
        return true
    }

    var zTree, rMenu;
    $(document).ready(function () {
        $.fn.zTree.init($("#treeJobScript"), js_setting);
        zTree = $.fn.zTree.getZTreeObj("treeJobScript");
        rMenu = $("#rMenu");
    });

    // 跟新/新建节点
    function zTreeBeforeRename(treeId, treeNode, newName, isCancel) {
        if (newName.trim() == '') return false;
        if (!isCancel) {
            var data = {
                id: treeNode.id,
                name: newName,
                pid: treeNode.pid,
                isParent: treeNode.isParent ? 1 : 0,
                sort: treeNode.getPreNode() ? treeNode.getPreNode().sort + 1 : 1
            };
            $.ajax({
                type: 'POST',
                url: '/jobScript/update',
                data: data,
                dataType: 'json',
                success: function (data) {
                    treeNode.id = data.id;
                    treeNode.sort = data.sort;
                    toastr.success('Modify successfully!', 'Success')
                },
                error: function (err) {
                    toastr.error('An error has occurred.', 'Error!')
                }
            })
        }
        return true
    }

    function zTreeOnExpand(event, treeId, treeNode) {
        if (treeNode.isAdd) {
            delete treeNode.isAdd;
            var zTree = $.fn.zTree.getZTreeObj(treeId);
            var name = treeNode.children ? treeNode.children[treeNode.children.length - 1].name : '';
            var newNodes = zTree.addNodes(treeNode, {name: name}, true);
            zTree.editName(newNodes[0]);
        }
    }

    function zTreeBeforeDrop(treeId, treeNodes, targetNode, moveType) {
        if (targetNode == null || moveType == "inner") return false; //禁止将节点拖拽成为根节点
        // if(treeNodes[0].type!=targetNode.type) return false; //禁止跨节点拖拽
        // if(treeNodes[0].level!=targetNode.level) return false; //禁止将节点拖拽成为子节点
        var data = {
            id: treeNodes[0].id,
            pid: treeNodes[0].pid,
            targetPid: targetNode.pid,
            sort: treeNodes[0].sort,
            targetSort: targetNode.sort,
            name: treeNodes[0].name
        }
        $.ajax({
            type: 'POST',
            url: '/jobScript/drag',
            data: data,
            success: function (data) {
                toastr.success('Modify successfully!', 'Success')
            },
            error: function (err) {
                toastr.error('An error has occurred.', 'Error!')
            }
        })
        return true
    };

    //保存iql
    function saveScript() {
        var node = zTree.getSelectedNodes()[0];
        if(node == null || node.isParent) {
            toastr.error('请先选择一个文件再保存！', 'Alarm!')
            return false;
        }
        $.post('/jobScript/updateSript', {
            id: node.id,
            script: window.editor.getValue()
        }, function (data, status) {
            if (status == "success") {
                toastr.success('Modify successfully!', 'Success')
            } else {
                toastr.error('An error has occurred.', 'Error!')
            }
        })
    }

</SCRIPT>

<script> // 鼠标拉伸代码框高度
    $(function(){
        var src_posi_Y = 0, dest_posi_Y = 0, move_Y = 0, is_mouse_down = false, destHeight = 30;
        $(".ui-draggable")
            .mousedown(function(e){
                src_posi_Y = e.pageY;//鼠标指针的位置
                is_mouse_down = true;
            });
        $(document).bind("click mouseup",function(e){
            if(is_mouse_down){
                is_mouse_down = false;
            }
        }).mousemove(function(e){
                dest_posi_Y = e.pageY;
                move_Y = src_posi_Y - dest_posi_Y;
                src_posi_Y = dest_posi_Y;
                destHeight = $(".CodeMirror").height() - move_Y;
                if(is_mouse_down){
                    $(".CodeMirror").css("height", destHeight > 250 ? destHeight : 250);
                    $(".CodeMirror-scroll").css("height", destHeight > 250 ? destHeight : 250);
                }
            });
    });

$(function(){
    var src_posi_X = 0, dest_posi_X = 0, move_X = 0, is_mouse_down = false, destWidth = 30;
    $(".ui-draggable-x")
        .mousedown(function(e){
            src_posi_X = e.pageX;//鼠标指针的位置
            is_mouse_down = true;
        });
    $(document).bind("click mouseup",function(e){
        if(is_mouse_down){
            is_mouse_down = false;
        }
    }).mousemove(function(e){
        dest_posi_X = e.pageX;
        move_X = src_posi_X - dest_posi_X;
        src_posi_X = dest_posi_X;
        console.log(dest_posi_X + ' -- ' + $(window).width());
        destWidth = dest_posi_X > 200 ? dest_posi_X : 200;
        destWidth = destWidth < 400 ? destWidth : 400;
        if(is_mouse_down){
            $("#body_left").width(destWidth);
            $("#body_right").width($(window).width() - destWidth - 10)
        }
    });
});
</script>

<script type="text/javascript">
    $(function () {
        window.operateEvents_stop_streamjob = {
            //加载历史查询结果
            'click .RoleOfstopStreamJob': function (e, value, row, index) {
                $.post("/stopStreamJob", {engineInfo: row.engineInfo, name: row.name, uid: row.uid}, function (data) {
                    if (data.isSuccess) {
                        loadActiveStreamJob();
                    } else {
                        $("#errorMessage").show();
                        $("#errorMessage pre").html(data.data)
                    }
                })
            }
        };


        $('.tab_stream_job').click(function (e) {
            loadActiveStreamJob();
        })

        loadActiveStreamJob();
        //加载活跃的StreamJob
        function loadActiveStreamJob() {
            $("#active-streamjob-table").bootstrapTable("destroy");
            $("#active-streamjob-table").bootstrapTable({
                method: 'get',
                cache: false,
                striped: true, //是否显示行间隔色
                sidePagination: 'server',
                url: '/getActiveStreams',
                dataType: 'json',
                columns: [
                    {
                        field: 'name',
                        title: 'StreamName',
                        align: 'center',
                        width: 50
                    },
                    {
                        field: 'engineInfo',
                        title: 'engineInfo',
                        visible: false
                    },
                    {
                        field: 'uid',
                        title: 'uid',
                        visible: false
                    },
                    {
                        field: 'uid',
                        title: '操作',
                        align: 'center',
                        width: 50,
                        events: operateEvents_stop_streamjob,
                        formatter: operateFormatter_stop_streamjob
                    }
                ]
            });
        }

    });

    var obj;
    var varis = [];
    ko.applyBindings(new addVariables());

    $.getJSON("/autoCompletehiveMetadata", {}, function (result) {
        var myTextarea = document.getElementById('iql');
        window.editor = CodeMirror.fromTextArea(myTextarea, {
            mode: 'text/x-hive',
            lineNumbers: true,
            indentWithTabs: true,
            smartIndent: true,
            matchBrackets: true,
            autofocus: true,
            styleActiveLine: true,
            lineWrapping: true,
            extraKeys: {"Ctrl-Space": "autocomplete"},
            hintOptions: {
                tables: result
            }
        });
        window.editor.on("keyup", autocomplete);
        window.editor.on("change", change);
    });

    function change(cm, event) {
        // $("#iql").attr("rows", window.editor.lastLine());
        var r = /\$\{([\s\S]*?)\}/g;
        var kvdata = {};
        var list = $("#variable ul li");
        list.each(function () {
            var value = $(this).children(".input-prepend ").children("input").val();
            var name = $(this).children(".input-prepend ").children("span").text();
            kvdata[name] = value;
        });
        obj.variables.removeAll();
        var vSet = {};
        var hasVariable = false;
        while ((result = r.exec(window.editor.getValue())) != null) {
            if (!vSet[result[1]]) {
                hasVariable = true;
                obj.variables.push({name: result[1], value: kvdata[result[1]]});
                vSet[result[1]] = 'a';
            }
        }
        if (hasVariable) {
            $("#variable").show()
        } else {
            $("#variable").hide()
        }
    }

    function addVariables() {
        var self = this;
        obj = this;
        self.variables = ko.observableArray([]);
    }

    $(function () {
        window.operateEvents_loadresult = {
            //加载历史查询结果
            'click .RoleOfloadHistory': function (e, value, row, index) {
                $("#errorMessage").hide();
                $("#execForm, .loading").toggle();
                $.post("/loadresult", {
                    schema: row.schema,
                    hdfsPath: row.hdfsPath,
                    dataType: row.dataType,
                    id: row.id
                }, function (data) {
                    $("#execForm, .loading").toggle();
                    $("#result-content").hide();
                    $("#result-content pre").html("");
                    $("#results-list-table").bootstrapTable("destroy")
                    $("#downloadForm").hide();
                    if (data.isSuccess) {
                        if (row.dataType == "preData") {
                            $("#results-tab").tab("show");
                            $("#result-content").show();
                            $("#result-content pre").html(data.data)
                        } else {
                            hdfsPath = row.hdfsPath;
                            schema = row.schema;
                            $("#results-tab").tab("show");
                            loadResultsTable(data.schema, JSON.parse(data.data))
                        }
                    } else {
                        $("#errorMessage").show();
                        $("#errorMessage pre").html(data.data)
                    }
                })
            },
            //删除历史查询
            'click .RoleOfdeleteHistory': function (e, value, row, index) {
                $.post("/deletehistoryiql", {id: row.id}, function (data) {
                    $("#history-list-table").bootstrapTable("refresh")
                })
            }
            ,
            //结果分享
            'click .RoleOfshareResult': function (e, value, row, index) {
                $.ajax({
                    type: 'POST',
                    url: '/shareResult',
                    data: {'id':row.id},
                    dataType: 'json',
                    success: function (res) {
                        $("#urlSign").val(res.urlSign)
                        $("#modal-share").modal("show");
                    },
                    error:function (err) {
                        $("#urlSign").val("抱歉，未获取到连接")
                        $("#modal-share").modal("show");
                    }
                })
            }
        };

        //加载历史iql和保存的iql
        loadHistoryTable();

        //行点击事件，将对应的iql显示在编辑框内
        $('#history-list-table').on('click-row.bs.table', function (e, row, element) {
            window.editor.setValue(row.iql);
            $("#queryId").val("");
            $("#queryName").val("");
            $("#queryDescription").val("");
            if (row.mode == "iql") {
                $(".btn-group").find("label").eq(0).addClass("active");
                $(".btn-group").find("label").eq(1).removeClass("active");
            } else {
                $(".btn-group").find("label").eq(1).addClass("active");
                $(".btn-group").find("label").eq(0).removeClass("active");
            }
            obj.variables.removeAll();
            $.each(JSON.parse(row.variables), function (index, data) {
                obj.variables.push({name: data.name, value: data.value});
            });
        });
        $('#saved-list-table').on('click-row.bs.table', function (e, row, element) {
            window.editor.setValue(row.iql);
            $("#queryId").val(row.id);
            $("#queryName").val(row.name);
            $("#queryDescription").val(row.description);
            if (row.mode == "iql") {
                $(".btn-group").find("label").eq(0).addClass("active");
                $(".btn-group").find("label").eq(1).removeClass("active");
            } else {
                $(".btn-group").find("label").eq(1).addClass("active");
                $(".btn-group").find("label").eq(0).removeClass("active");
            }
        });

        $.fn.zTree.init($("#treeHiveDB"), setting);
    });

    // 执行IQL
    function execIQL() {

        var iqlText;
        if (window.editor.getSelection() == "") {
            iqlText = window.editor.getValue()
        } else {
            iqlText = window.editor.getSelection()
        }
        varis = [];
        var list = $("#variable ul li");
        list.each(function () {
            var value = $(this).children(".input-prepend ").children("input").val();
            var name = $(this).children(".input-prepend ").children("span").text();
            varis.push({name: name, value: value})
        });

        $("#errorMessage").hide();
        $("#errorMessage pre").html("");
        $("#result-content").hide();
        $("#result-content pre").html("");
        $("#execForm, .loading").toggle();
        $("#downloadForm").hide();
        $.post("/query", {
            iql: iqlText,
            mode: $(".btn-group").children(".active").children("input").val(),
            variables: JSON.stringify(varis),
            descrption: $("#queryDescription").val()
        }, function (data) {
            if (data.isSuccess) {
                $("#iqlId").val(data.engineInfoAndGroupId);
                $.post("/getresult", {engineInfoAndGroupId: data.engineInfoAndGroupId}, function (data) {
                    $("#execForm, .loading").toggle();
                    if (data.isSuccess) {
                        $("#results-list-table").bootstrapTable("destroy");
                        if (data.dataType=="preData") {
                            $("#results-tab").tab("show");
                            $("#result-content").show();
                            $("#result-content pre").html(data.data)
                        } else {
                            $("#results-tab").tab("show");
                            hdfsPath = data.hdfsPath;
                            schema = data.schema;
                            loadResultsTable(data.schema, JSON.parse(data.data))
                        }
                    } else {
                        $("#errorMessage").show();
                        $("#errorMessage pre").html(data.data)
                    }
                });
            } else {
                $("#execForm, .loading").toggle();
                $("#errorMessage").show();
                $("#errorMessage pre").html(data.data)
            }
        })
    }

    // 美化IQL
    function formatIQL() {
        $.post("/formatSql", {iql: window.editor.getValue()}, function (data) {
            window.editor.setValue(data.iql);
        })
    }

    // 停止query
    function stopQuery() {
        $.post("/stopquery", {engineInfoAndGroupId: $("#iqlId").val()}, function (data) {
        })
    }

    //加载结果数据
    function loadResultsTable(schema, data) {
        var columns = [];
        var headTitles = schema.split(",");
        $.each(headTitles, function (i, name) {
            columns.push({
                title: name,
                field: name,
                width: 200,
                align: 'center'
            })
        });
        $("#results-list-table").bootstrapTable({
            method: 'get',
            cache: false,
            striped: true, //是否显示行间隔色
            pageList: [10, 20, 50, 100],
            pageSize: 20,
            pagination: true,
            sidePagination: 'client',
            dataType: 'json',
            columns: columns
        });
        $("#results-list-table")
            .bootstrapTable("load", data);

        $("#downloadForm").show()
    }

    //加载历史数据
    function loadHistoryTable() {
        $("#history-list-table").bootstrapTable({
            method: 'get',
            cache: false,
            striped: true, //是否显示行间隔色
            pageList: [10, 20, 50, 100],
            pageSize: 20,
            showRefresh: true,
            search: true,
            strictSearch: true,
            pagination: true,
            sidePagination: 'server',
            url: '/history',
            dataType: 'json',
            queryParams: function (params) {
                // var params = {
                //     search:$(".form-control").val()
                // };
                var param = {
                    offset: params.offset,
                    limit: params.limit,
                    order: params.order,
                    search: $(".form-control").val()
                };
                return param;
            },
            columns: [
                {
                    field: 'startTime',
                    title: '开始时间',
                    width: 40,
                    formatter: function (value, row, index) {
                        return '<span title="' + timestampToTime(value) + '">' + timeago(value) + '</span>'
                    }
                },
                {
                    field: 'isSuccess',
                    title: '执行结果',
                    width: 40,
                    formatter: function (value, row, index) {
                        if (value)
                            return '<span class="text-success" title="successful"><i class="glyphicon glyphicon-ok"></i></span>';
                        else
                            return '<span class="text-warning" title="failed"><i class="glyphicon glyphicon-exclamation-sign"></i></span>'
                    }
                },
                {
                    field: 'takeTime',
                    title: '耗时',
                    width: 40,
                    formatter: function (value, row, index) {
                        return '<span>' + (value/1000).toFixed(1) + ' s' + '</span>'
                    }
                },
                {
                    field: 'iql',
                    title: '执行操作',
                    width: 300
                },
                {
                    field: 'hdfsPath',
                    visible: false
                },
                {
                    field: 'tableSchema',
                    visible: false
                },
                {
                    field: 'variables',
                    visible: false
                },
                {
                    field: 'dataType',
                    visible: false
                },
                {
                    field: 'id',
                    visible: false
                },
                {
                    field: 'id',
                    title: '操作',
                    align: 'center',
                    width: 120,
                    events: operateEvents_loadresult,
                    formatter: operateFormatter_loadresult
                }
            ]
        });
    }

    //下载结果文件
    function downloadFile(fileType) {
        var formParams = {
            hdfsPath: hdfsPath,
            schema: schema,
            fileType: fileType
        }
        var url = addParamsToUrl('/fileDownload', formParams);
        window.location.href = url
    }

    //为行添加加载结果操作
    function operateFormatter_loadresult(value, row, index) {
        return [
            '<button type="button" class="RoleOfloadHistory btn btn-ms btn-default" style="margin-right:15px;">result</button>',
            '<button type="button" class="RoleOfdeleteHistory btn btn-ms btn-default" style="margin-right:15px;">delete</button>',
            '<button type="button" class="RoleOfshareResult btn btn-ms btn-default" style="margin-right:15px;">share</button>'
        ].join('');
    }

    //为行添加结束StreamJob操作
    function operateFormatter_stop_streamjob(value, row, index) {
        return [
            '<button type="button" class="RoleOfstopStreamJob btn btn-ms btn-default" style="margin-right:10px;">stop</button>'
        ].join('');
    }
</script>

<script>

    function zTreeOnClick(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        zTree.expandNode(treeNode, null, null, null);
    }

    function zTreeOnNodeCreated(event, treeId, treeNode) {
        // $('#' + treeNode.tId + '_ico').css("display", "none");
    }

    var setting = {
        view: {
            nameIsHTML: true
        },
        check: {
            enable: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        edit: {
            enable: false
        },
        callback: {
            onClick: zTreeOnClick,
            onNodeCreated: zTreeOnNodeCreated
        },
        async: {
            enable: true,
            url: '/hiveMetadata',
            type: 'get'
        }
    };
</script>

<script>
    function copyUrl() {
        var obj = document.getElementById("urlSign");
        obj.select();
        try{
            if(document.execCommand("Copy","false",null)){
                toastr.success('Reproduce successfully!', 'Success')
            }else{
                toastr.error('Reproduce filed!', 'WARN')
            }
        }catch(err){
            toastr.error('Reproduce error!', 'ERROR')
        }
    }
</script>


</body>
</html>
